package com.elinkway.infinitemovies.ui.activity.play;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bean.Episode;
import com.elinkway.infinitemovies.bean.PlayStatusReporter;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.bigdata.BigDataPlayReporter;
import com.elinkway.infinitemovies.bigdata.BigDataUtils;
import com.elinkway.infinitemovies.download.Constants;
import com.elinkway.infinitemovies.http.requesttask.ReportPlayStatusTask;
import com.elinkway.infinitemovies.listener.MyOnClickListener;
import com.elinkway.infinitemovies.push.PushStatsPoster;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.bean.MyDataRecord;
import com.elinkway.infinitemovies.selfdata.bean.OnePointRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.share.SharePopupWindow;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.PushUtil;
import com.elinkway.infinitemovies.utils.ReportUtil;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.VideoEnabledWebChromeClient;
import com.elinkway.infinitemovies.view.VideoEnabledWebChromeClient.ToggledFullscreenCallback;
import com.elinkway.infinitemovies.view.VideoEnabledWebView;
import com.le123.ysdq.R;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

public class PlayActivityFroWebView extends Activity implements VideoEnabledWebChromeClient.OnTitleChangeListener{
	VideoView video;

    private ImageView topBack;
    private ImageView topRefresh;
    private TextView tv_title;
    private TextView tv_url;
    private VideoEnabledWebView playWeb;
    private ProgressBar pg;
    private String url;
    private String mShareUrl;
    private String title;
    private String site;
    private float curr_x;
    private float curr_y;
    private float his_y;
    private float his_x;
    private RelativeLayout topbar;
    private VideoEnabledWebChromeClient client;
    private RelativeLayout nonVideoLayout;
    private FrameLayout videoLayout;
    private FrameLayout fyWebVideoControl;
    public CustomViewCallback mCallback;
    public RelativeLayout videoLoading;

    public View mView;


    private boolean isFulllScreen = false;
    private RelativeLayout lyWebVideoControl;
    private WebVideoController mWebVideoController; // web中Video的播放器控制
    private boolean isIQiYiSdk = false; // 是否是爱奇艺sdk
    public static final String TAG_SDK_IQIYI = "sdk_iqiyi"; //
    public static final String TAG_AID = "tag_aid"; //
    public static final String TAG_SITE_NAME = "tag_site_name"; //
    public static final String TAG_SCRIPT = "tag_script"; //
    private PlayStatusReporter mPlayStatusReport;
    private BigDataPlayReporter bigDataPlayReporter;
    private Episode mEpisode;
    private String mAid;
    private String mSiteName;
    private String mSiteUrl;
    private String mPageFrom;
    private PopupWindow mSharePopupWindow;
    private String mShareDesc;
    private String mSharePic;
    private String docid;
    private String impid;
    private String pageid;
    private static final String DEFAULT_SHAREPIC = "http://s.shandianshipin.cn/imgs/icon/daquan.png";
    private boolean isChangePic;
    private String mToType;

    private long startTime;
    private long endTime;
    public static void openActivity(Activity activity,Episode episode,boolean isIQiYiSdk,String aid,String name,String siteName,
                                    String script,String site) {
        Intent intent = new Intent(activity, PlayActivityFroWebView.class);
        intent.putExtra(Episode.TAG,episode);
        intent.putExtra(TAG_SDK_IQIYI,isIQiYiSdk);
        intent.putExtra(TAG_AID,aid);
        intent.putExtra(TAG_SITE_NAME,siteName);
        intent.putExtra(TAG_SCRIPT,script);
        intent.putExtra("title",name);
        intent.putExtra("site",site);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);
        startTime=System.currentTimeMillis();
        Bundle bundle = getIntent().getExtras();
        url = bundle.getString("url");
        setShareUrl(url);
        title = bundle.getString("title");
        site = bundle.getString("site");
        mPageFrom = bundle.getString("from");
        mSharePic = bundle.getString("pic");
        mShareDesc = bundle.getString("summary");
        mToType = bundle.getString("totype");
        if(TextUtils.isEmpty(mToType)){
            mToType = "video";
        }
        if (MoviesConstant.ONEPOINT_TAG.equals(mPageFrom)){
            pageid = bundle.getString("pageid");
            impid = bundle.getString("impid");
            docid = bundle.getString("docid");
            userid = bundle.getString("userid");
        }
        mSiteName = bundle.containsKey(TAG_SITE_NAME) ? bundle.getString(TAG_SITE_NAME) : "";
        isIQiYiSdk = bundle.containsKey(TAG_SDK_IQIYI) ? bundle.getBoolean(TAG_SDK_IQIYI) : false;
        if (isIQiYiSdk) {
            mEpisode = bundle.containsKey(Episode.TAG) ? (Episode)bundle.getSerializable(Episode.TAG) : null;
            mAid = bundle.containsKey(TAG_AID) ? bundle.getString(TAG_AID) : "";

            if (mEpisode != null) {
                url = !TextUtils.isEmpty(mEpisode.getExternalId()) ? mEpisode.getExternalId() : "";
                if (TextUtils.isEmpty(url) && !TextUtils.isEmpty(mEpisode.getPlay_url())) {
                    url = mEpisode.getPlay_url() + Constants.TAG_IQIYI_SDK_PARAM;
                }
            }
            if (!TextUtils.isEmpty(mSiteName)) {
                mSiteUrl = mSiteName + ":" + url;
            }
        }
        // 友盟上报
        // 是否来自推送
        PushStatsPoster.postPushClickStats(bundle, UmengEventPoster.PUSH_TYPE_LINK);
        initView();
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            topbar.setVisibility(View.GONE);
        }
        playWeb.loadUrl(url);
    }

    private void initView() {
        topbar = (RelativeLayout) findViewById(R.id.play_topbar);
        topBack = (ImageView) findViewById(R.id.play_back);
        topRefresh = (ImageView) findViewById(R.id.play_refresh);
        tv_title = (TextView) findViewById(R.id.play_title);
        tv_url = (TextView) findViewById(R.id.play_url);
        playWeb = (VideoEnabledWebView) findViewById(R.id.play_webview);
        pg = (ProgressBar) findViewById(R.id.play_progress);
        videoLayout = (FrameLayout) findViewById(R.id.videoLayout);
        nonVideoLayout = (RelativeLayout) findViewById(R.id.nonVideoLayout);
        videoLoading = (RelativeLayout) UIs.inflate(this, R.layout.video_loading_layout, null);
        tv_title.setText(title);
        tv_url.setText(url);
        if (isIQiYiSdk) {
            mWebVideoController = new WebVideoController(this, playWeb,url,title,isIQiYiSdk);
            View viewLy = View.inflate(PlayActivityFroWebView.this,R.layout.web_full_screen_control,null);
            client = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, videoLoading, pg,viewLy , mWebVideoController,site,isIQiYiSdk);
            client.setOnToggledFullscreen(new MyToggledFullscreenCallback());
        } else if (MoviesConstant.ONEPOINT_TAG.equals(mPageFrom)) {
            client = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, videoLoading, pg);
            client.setOnToggledFullscreen(new MyToggledFullscreenCallback());
        } else {
            client = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, videoLoading, pg);
        }
        client.setOnTitleChangerListener(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        topBack.setOnClickListener(new MyOnClickListener() {

            @Override
            public void onClickListener(View v) {
                performBack();
            }
        });
        topRefresh.setOnClickListener(new MyOnClickListener() {

            @Override
            public void onClickListener(View v) {
                if (mWebVideoController != null) {
                    mWebVideoController.setVideoReady(false);
                }
                playWeb.reload();
            }
        });
        playWeb.getSettings().setJavaScriptEnabled(true);// 设置使用够执行JS脚本
        if (!(!StringUtil.isEmpty(site) && site.equals("nets"))) {
            playWeb.setWebViewClient(new PlayWebViewClient());
        }
        playWeb.setWebChromeClient(client);
        playWeb.getSettings().setPluginState(PluginState.OFF);
        playWeb.getSettings().setDomStorageEnabled(true);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH && !checkflash()) {
            UIs.showToast(R.string.flash_required);
        }

        if(MoviesConstant.ONEPOINT_TAG.equals(mPageFrom)){
            topbar.setBackgroundColor(getResources().getColor(R.color.white));
            tv_url.setVisibility(View.GONE);
            tv_title.setTextColor(getResources().getColor(R.color.black));
            tv_title.setVisibility(View.GONE);
            topBack.setImageResource(R.drawable.left_back_icon_selector);
            SharePopupWindow mShareWindow = new SharePopupWindow(this, 3);
            mSharePopupWindow = mShareWindow.initPopWindow();
            topRefresh.setImageResource(R.drawable.share_icon);
            topRefresh.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != mSharePopupWindow) {
                        mSharePopupWindow.showAtLocation(topRefresh, Gravity.CENTER, 0, 0);
                    }
                }
            });
            if(NetWorkTypeUtils.TYPE_MOBILE == NetWorkTypeUtils.reportNetType(this)){
                ToastUtil.showShortToast(this, "正在使用移动流量");
            }
            mWebVideoController = new WebVideoController(this, playWeb,url,MoviesConstant.ONEPOINT_TAG,false);
        }
    }

    @Override
    public void OnTitleChange(String title) {
        if (tv_title != null && !TextUtils.isEmpty(title)) {
            tv_title.setText(title);
            this.title = title;
        }
    }

    private class PlayWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Uri uri = Uri.parse(url);
            String scheme = uri.getScheme();
            if (scheme.equals("http") || scheme.equals("https")) {
                tv_url.setText(url);
                if(MoviesConstant.ONEPOINT_TAG.equals(mPageFrom)){
                    setShareUrl(url);
                    if("video".equals(mToType) && isChangePic || "author".equals(mToType)){
                        setSharePic(DEFAULT_SHAREPIC);
                        mShareDesc = Utils.getTodayTime();
                    }
                    isChangePic = true;
                }
                return false;
            } else {
                return true;
            }
        }

        @Override
        // 转向错误时的处理
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if ((isIQiYiSdk && mWebVideoController != null) || MoviesConstant.ONEPOINT_TAG.equals(mPageFrom)) {
                mWebVideoController.addVideoReadyListener();
            }
        }
    }

    public void setStatistics() {
        mPlayStatusReport = new PlayStatusReporter();
        bigDataPlayReporter = new BigDataPlayReporter();
        // 服务器上报
        mPlayStatusReport.setAction(MoviesConstant.STATE_ACTION_PLAY);
        mPlayStatusReport.setSubsrc(Constants.TAG_IQIYI_SDK + Constants.TAG_SDK);
        mPlayStatusReport.setStartPlayTime(System.currentTimeMillis());
        mPlayStatusReport.setState(MoviesConstant.PLAY_SUCCESS_STATE);
        if (mEpisode != null) {
            if (!TextUtils.isEmpty(mEpisode.getCloudId())) {
                mPlayStatusReport.setmCloudId(mEpisode.getCloudId());
            }
            if (!TextUtils.isEmpty(mEpisode.getPorder())) {
                mPlayStatusReport.setPorder(mEpisode.getPorder());
            }
            if (!TextUtils.isEmpty(mEpisode.getPlay_url())) {
                mPlayStatusReport.setVid(mEpisode.getPlay_url());
            }
            if (!TextUtils.isEmpty(mEpisode.getVid())) {
                bigDataPlayReporter.setVid(mEpisode.getVid());
            }
        }
        if (!TextUtils.isEmpty(mAid)) {
            mPlayStatusReport.setAid(mAid);
            bigDataPlayReporter.setPid(mAid).setVid(mAid);
        } else {
            bigDataPlayReporter.setPid("-").setVid("-");
        }
        new ReportPlayStatusTask(this, mPlayStatusReport).start();
        // 大数据上报
        bigDataPlayReporter.setNt(BigDataUtils.getNetType(this));
        bigDataPlayReporter.setPlayType(BigDataConstants.TY_ONLINE);
        bigDataPlayReporter.setSource(Constants.TAG_IQIYI_SDK);
        bigDataPlayReporter.setPy(bigDataPlayReporter.getPy() + "&player=sdk");
        bigDataPlayReporter.setAc(BigDataConstants.PLAY_AC_PLAY);
        bigDataPlayReporter.onPlayProcess();
    }


    @Override
    public void onBackPressed() {
        finish();
    }

    private boolean checkflash() {
        PackageManager pm = getPackageManager();
        List<PackageInfo> infoList = pm.getInstalledPackages(PackageManager.GET_SERVICES);
        for (PackageInfo info : infoList) {
            if ("com.adobe.flashplayer".equals(info.packageName)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            playWeb.getClass().getMethod("onPause")
                    .invoke(playWeb, (Object[]) null);
            playWeb.clearHistory();
            nonVideoLayout.removeView(playWeb);
            playWeb.removeAllViews();
            playWeb.destroy();
            playWeb = null;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        playWeb.pauseTimers();
        try {
            playWeb.getClass().getMethod("onPause")
                    .invoke(playWeb, (Object[]) null);
            playWeb.pauseTimers();
            playWeb.stopLoading();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        pageEnd();
        MobclickAgent.onPause(this);
    }

    private void pageEnd() {
        if (!TextUtils.isEmpty(mPageFrom)&&MoviesConstant.ONEPOINT_TAG.equals(mPageFrom)){
            OnePointRecord record = MyDataRecordCreater.build(OnePointRecord.class);
            record.setCur_url("yidianweb");
            record.setResidenceTime(String.valueOf((System.currentTimeMillis() - startTime)/1000));
            RealmDaoManager.addMyDataRecord(record);

            //上报：退出视频流
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("pageid",pageid);
                jsonObject.put("impid", impid);
                jsonObject.put("docid", docid);
                jsonObject.put("subType","play");
                jsonObject.put("srcType","1");
                jsonObject.put("userid",userid);
                jsonObject.put("timeElapsed",String.valueOf((System.currentTimeMillis() - startTime)/1000));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            ReportUtil.report(jsonObject);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        playWeb.resumeTimers();
        try {

            playWeb.getClass().getMethod("onResume")
                    .invoke(playWeb, (Object[]) null);
            super.onResume();

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        MobclickAgent.onResume(this);
    }

    private class MyToggledFullscreenCallback implements ToggledFullscreenCallback {

        @Override
        public void toggledFullscreen(boolean fullscreen) {

            if (fullscreen) {
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            } else {
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        }

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            topbar.setVisibility(View.GONE);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            topbar.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK ) {
            performBack();
        }
        return false;
    }

    private void performBack() {
        //special logic for yidian
        if (MoviesConstant.ONEPOINT_TAG.equals(mPageFrom)) {
            //exit fullscreen mode first
            if (!client.onBackPressed()) {
                String bottomIndex = null;
                boolean isFromOnePointPush = getIntent().getBooleanExtra(MoviesApplication.START_FROM_NOTIFICATION, false);
                if (isFromOnePointPush) {
                    bottomIndex = PushUtil.TAB_INDEX_ONEPOINT;
                    MoviesApplication.getInstance().startMainFromPushBack(this, bottomIndex);
                } else {
                    finish();
                }
            }
        } else {
            finish();
        }
    }

    public String getShareTitle() {
        if(!TextUtils.isEmpty(title)){
            return title.replace("一点资讯", "影视大全");
        }else{
            return  "分享了一个链接";
        }
    }

    public String getSharePic() {
        if (TextUtils.isEmpty(mSharePic)) {
            return "";
        }
        return mSharePic;
    }

    public void setSharePic(String pic){
        mSharePic = pic;
    }

    public String getShareDesc() {
        if(TextUtils.isEmpty(mShareDesc)){
            return Utils.getTodayTime();
        }
        return mShareDesc;
    }

    public void setShareDesc(String desc){
        mShareDesc = desc;
    }

    public String getShareUrl() {
        if (TextUtils.isEmpty(mShareUrl)) {
            return "";
        }
        return mShareUrl;
    }
    public void setShareUrl(String url){
        mShareUrl = url;
    }

    public String getPageid() {
        if (TextUtils.isEmpty(pageid)) {
            return "";
        }
        return pageid;
    }
    public String getImpid() {
        if (TextUtils.isEmpty(impid)) {
            return "";
        }
        return impid;
    }
    public String getDocid() {
        if (TextUtils.isEmpty(docid)) {
            return "";
        }
        return docid;

    }

    public String getFrom() {
        if (TextUtils.isEmpty(mPageFrom)) {
            return "";
        }
        return mPageFrom;

    }

    private String userid;

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }


}
